package com.mgface.zookeeper;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

import org.apache.log4j.Logger;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;

/**
 * Hello world!
 *
 */
public class App {
	private static Logger log= Logger.getLogger(App.class);
	public static void main(String[] args) throws IOException, InterruptedException, Exception {
		CountDownLatch cdl = new CountDownLatch(1);
		ZooKeeper zk = new ZooKeeper("192.168.56.101:2182", 2_000, e->{
			log.info("接收到的event:"+e);
			if(e.getState()==KeeperState.SyncConnected){
				cdl.countDown();
			}
		});
		log.info("ZK状态:"+zk.getState().toString());
		cdl.await();
		log.info("zookeeper session established");
		
		long sessionId = zk.getSessionId();
		byte[] bytes = zk.getSessionPasswd();
		//恢复session会话
		ZooKeeper zk2 = new ZooKeeper("192.168.56.101:2182", 2_000, e->{
			log.info("zk2接收到的event:"+e);
		}, sessionId, bytes);
		//错误连接，没有恢复成功
		ZooKeeper zk3 = new ZooKeeper("192.168.56.101:2182", 2_000, e->{
			log.info("zk3接收到的event:"+e);
		}, 1000L, bytes);
		
		Thread.sleep(15_000);
		
		//创建节点，同步方法
//		String path = zk2.create("/zk/001~", "001".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
//		log.info("success create znode:"+path);
//		String path2 = zk2.create("/zk/001~", "001".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
//		log.info("success create znode:"+path2);
		
		//创建节点，异步方法
		zk.create("/zk/002", "002".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT,(rc,_path,ctx,name)->{
			log.info("create path result:["+rc+","+_path+","+ctx+",real path name:"+name);
		},"I am context");
		Thread.sleep(10_000);
	}
}
